# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 个人资料表单

个人资料管理相关的表单定义
包括基本信息编辑、密码修改、头像上传等表单
"""

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import (
    StringField, TextAreaField, SelectField, IntegerField,
    PasswordField, ValidationError
)
from wtforms.validators import (
    DataRequired, Length, Email, NumberRange, Optional,
    Regexp, EqualTo
)
from flask_login import current_user
from decimal import Decimal

from app.models.user import User
from app.models.campus import Campus


class ProfileBasicForm(FlaskForm):
    """基本资料编辑表单"""

    real_name = StringField(
        '真实姓名',
        validators=[
            DataRequired(message='请输入真实姓名'),
            Length(2, 50, message='姓名长度必须在2-50个字符之间')
        ],
        render_kw={
            'placeholder': '请输入真实姓名',
            'class': 'form-control'
        }
    )

    phone = StringField(
        '手机号',
        validators=[
            DataRequired(message='请输入手机号'),
            Regexp(r'^1[3-9]\d{9}$', message='请输入正确的手机号格式')
        ],
        render_kw={
            'placeholder': '请输入11位手机号',
            'class': 'form-control',
            'readonly': True  # 手机号一般不允许修改
        }
    )

    email = StringField(
        '邮箱',
        validators=[
            Optional(),
            Email(message='请输入正确的邮箱格式'),
            Length(max=100, message='邮箱长度不能超过100个字符')
        ],
        render_kw={
            'placeholder': '请输入邮箱地址（可选）',
            'class': 'form-control'
        }
    )

    gender = SelectField(
        '性别',
        choices=[
            ('', '请选择'),
            ('male', '男'),
            ('female', '女')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    age = IntegerField(
        '年龄',
        validators=[
            Optional(),
            NumberRange(min=3, max=80, message='年龄必须在3-80之间')
        ],
        render_kw={
            'placeholder': '请输入年龄',
            'class': 'form-control',
            'min': '3',
            'max': '80'
        }
    )

    bio = TextAreaField(
        '个人简介',
        validators=[
            Optional(),
            Length(max=500, message='个人简介不能超过500个字符')
        ],
        render_kw={
            'placeholder': '介绍一下自己（可选）',
            'class': 'form-control',
            'rows': '3'
        }
    )

    def validate_email(self, field):
        """验证邮箱唯一性"""
        if field.data:
            user = User.query.filter_by(email=field.data).first()
            if user and user.id != current_user.id:
                raise ValidationError('该邮箱已被其他用户注册')


class CoachProfileForm(FlaskForm):
    """教练资料编辑表单（继承基本表单功能）"""

    real_name = StringField(
        '真实姓名',
        validators=[
            DataRequired(message='请输入真实姓名'),
            Length(2, 50, message='姓名长度必须在2-50个字符之间')
        ],
        render_kw={
            'placeholder': '请输入真实姓名',
            'class': 'form-control'
        }
    )

    phone = StringField(
        '手机号',
        validators=[
            DataRequired(message='请输入手机号'),
            Regexp(r'^1[3-9]\d{9}$', message='请输入正确的手机号格式')
        ],
        render_kw={
            'placeholder': '请输入11位手机号',
            'class': 'form-control',
            'readonly': True
        }
    )

    email = StringField(
        '邮箱',
        validators=[
            Optional(),
            Email(message='请输入正确的邮箱格式'),
            Length(max=100, message='邮箱长度不能超过100个字符')
        ],
        render_kw={
            'placeholder': '请输入邮箱地址（可选）',
            'class': 'form-control'
        }
    )

    gender = SelectField(
        '性别',
        choices=[
            ('', '请选择'),
            ('male', '男'),
            ('female', '女')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    age = IntegerField(
        '年龄',
        validators=[
            Optional(),
            NumberRange(min=18, max=70, message='教练年龄必须在18-70之间')
        ],
        render_kw={
            'placeholder': '请输入年龄',
            'class': 'form-control',
            'min': '18',
            'max': '70'
        }
    )

    coach_level = SelectField(
        '教练等级',
        choices=[
            ('junior', '初级教练'),
            ('middle', '中级教练'),
            ('senior', '高级教练')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    hourly_rate = StringField(
        '课时费(元/小时)',
        validators=[Optional()],
        render_kw={
            'placeholder': '例如：50.00',
            'class': 'form-control'
        }
    )

    experience_years = IntegerField(
        '执教年限',
        validators=[
            Optional(),
            NumberRange(min=0, max=50, message='执教年限必须在0-50年之间')
        ],
        render_kw={
            'placeholder': '请输入执教年限',
            'class': 'form-control',
            'min': '0',
            'max': '50'
        }
    )

    bio = TextAreaField(
        '个人简介',
        validators=[
            Optional(),
            Length(max=1000, message='个人简介不能超过1000个字符')
        ],
        render_kw={
            'placeholder': '介绍您的教学理念、特长和成就',
            'class': 'form-control',
            'rows': '4'
        }
    )

    teaching_style = TextAreaField(
        '教学风格',
        validators=[
            Optional(),
            Length(max=500, message='教学风格描述不能超过500个字符')
        ],
        render_kw={
            'placeholder': '描述您的教学方式和特点',
            'class': 'form-control',
            'rows': '3'
        }
    )

    achievements = TextAreaField(
        '个人成就',
        validators=[
            Optional(),
            Length(max=1000, message='个人成就不能超过1000个字符')
        ],
        render_kw={
            'placeholder': '列举您的主要成就和获奖经历',
            'class': 'form-control',
            'rows': '4'
        }
    )

    def validate_email(self, field):
        """验证邮箱唯一性"""
        if field.data:
            user = User.query.filter_by(email=field.data).first()
            if user and user.id != current_user.id:
                raise ValidationError('该邮箱已被其他用户注册')

    def validate_hourly_rate(self, field):
        """验证课时费格式"""
        if field.data:
            try:
                rate = Decimal(field.data)
                if rate < 0:
                    raise ValidationError('课时费不能为负数')
                if rate > 1000:
                    raise ValidationError('课时费不能超过1000元/小时')
            except (ValueError, TypeError):
                raise ValidationError('请输入正确的课时费格式')


class ChangePasswordForm(FlaskForm):
    """修改密码表单"""

    current_password = PasswordField(
        '当前密码',
        validators=[
            DataRequired(message='请输入当前密码')
        ],
        render_kw={
            'placeholder': '请输入当前密码',
            'class': 'form-control'
        }
    )

    new_password = PasswordField(
        '新密码',
        validators=[
            DataRequired(message='请输入新密码'),
            Length(8, 64, message='密码长度必须在8-64个字符之间'),
            Regexp(
                r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)',
                message='密码必须包含大小写字母和数字'
            )
        ],
        render_kw={
            'placeholder': '请输入新密码（8位以上，包含大小写字母和数字）',
            'class': 'form-control'
        }
    )

    confirm_password = PasswordField(
        '确认新密码',
        validators=[
            DataRequired(message='请确认新密码'),
            EqualTo('new_password', message='两次输入的密码不一致')
        ],
        render_kw={
            'placeholder': '请再次输入新密码',
            'class': 'form-control'
        }
    )

    def validate_current_password(self, field):
        """验证当前密码"""
        if not current_user.check_password(field.data):
            raise ValidationError('当前密码错误')

    def validate_new_password(self, field):
        """验证新密码不能与当前密码相同"""
        if current_user.check_password(field.data):
            raise ValidationError('新密码不能与当前密码相同')


class AvatarUploadForm(FlaskForm):
    """头像上传表单"""

    avatar = FileField(
        '头像',
        validators=[
            DataRequired(message='请选择头像文件'),
            FileAllowed(['jpg', 'jpeg', 'png', 'gif'], '只允许上传图片文件')
        ],
        render_kw={'class': 'form-control'}
    )

    crop_x = IntegerField(
        '裁剪X坐标',
        validators=[Optional()],
        render_kw={'type': 'hidden'}
    )

    crop_y = IntegerField(
        '裁剪Y坐标',
        validators=[Optional()],
        render_kw={'type': 'hidden'}
    )

    crop_width = IntegerField(
        '裁剪宽度',
        validators=[Optional()],
        render_kw={'type': 'hidden'}
    )

    crop_height = IntegerField(
        '裁剪高度',
        validators=[Optional()],
        render_kw={'type': 'hidden'}
    )


class AccountSettingsForm(FlaskForm):
    """账户设置表单"""

    # 通知设置
    email_notifications = SelectField(
        '邮件通知',
        choices=[
            ('all', '接收所有通知'),
            ('important', '仅重要通知'),
            ('none', '不接收通知')
        ],
        default='important',
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    sms_notifications = SelectField(
        '短信通知',
        choices=[
            ('all', '接收所有通知'),
            ('important', '仅重要通知'),
            ('none', '不接收通知')
        ],
        default='important',
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    # 隐私设置
    profile_visibility = SelectField(
        '资料可见性',
        choices=[
            ('public', '公开'),
            ('campus_only', '仅校区内可见'),
            ('private', '私有')
        ],
        default='campus_only',
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    show_phone = SelectField(
        '显示手机号',
        choices=[
            ('yes', '显示'),
            ('no', '不显示')
        ],
        default='no',
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    show_email = SelectField(
        '显示邮箱',
        choices=[
            ('yes', '显示'),
            ('no', '不显示')
        ],
        default='no',
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )


class DeleteAccountForm(FlaskForm):
    """注销账户表单"""

    current_password = PasswordField(
        '当前密码',
        validators=[
            DataRequired(message='请输入当前密码进行确认')
        ],
        render_kw={
            'placeholder': '请输入当前密码',
            'class': 'form-control'
        }
    )

    confirm_text = StringField(
        '确认注销',
        validators=[
            DataRequired(message='请输入确认文本')
        ],
        render_kw={
            'placeholder': '请输入"确认注销"',
            'class': 'form-control'
        }
    )

    delete_reason = TextAreaField(
        '注销原因',
        validators=[
            Optional(),
            Length(max=255, message='注销原因不能超过255个字符')
        ],
        render_kw={
            'placeholder': '请说明注销账户的原因（可选）',
            'class': 'form-control',
            'rows': '3'
        }
    )

    def validate_current_password(self, field):
        """验证当前密码"""
        if not current_user.check_password(field.data):
            raise ValidationError('当前密码错误')

    def validate_confirm_text(self, field):
        """验证确认文本"""
        if field.data != '确认注销':
            raise ValidationError('请输入正确的确认文本：确认注销')